// 价格
export function priceInput(value) {
  const priceInput = document.querySelectorAll(
    ".mantine-1i52ecs > .mantine-ysl0gg"
  )[0];
  if (priceInput) {
    console.log(priceInput, "priceInput  tradeeeeeeeeeeee");
    console.log(priceInput.value, "priceInput.value");

    setTimeout(() => {
      priceInput.value = value.toFixed(2);

      const event = new Event("input", { bubbles: true });
      priceInput.dispatchEvent(event);
    }, 100)

  } else {
    console.log("未找到.mantine-1i52ecs > .mantine-ysl0gg节点");
  }
}

import { property } from '@/content-scripts/components/trading/inStock/index.js'

// 可用
export function tradePanelAvailable(value, tab) {
  const tradePanel = document.querySelector("#multiCurrencyMarginModeSpotStep1 > div > span")
  console.log(value, 'tradePanelAvailableValue');

  console.log(tradePanel, "tradePanel");
  if (tradePanel) {
    if (tab == '市价') {
      const maxPurch = Number(value) / Number(localStorage.getItem('priceInput'))
      tradePanel.innerText = `${Number(value).toFixed(2)} USDT`;
      console.log(tradePanel.innerText, "tradePanel.innerText");
      aTurnoverObersver(value, tab, maxPurch)
    } else {
      let interval = setInterval(() => {
        const priceInput = document.querySelectorAll(
          ".mantine-1i52ecs > .mantine-ysl0gg"
        )[0];
        if (priceInput && priceInput.value != 0) {
          clearInterval(interval)
          console.log(priceInput.value, "priceInput.value");
          localStorage.setItem('priceInput', priceInput.value)
        }

      })


      console.log(Number(value) / Number(priceInput.value), 'wwwwwwwwwwwww');
      const maxPurch = Number(value) / Number(priceInput.value)
      property()

      tradePanel.innerText = `${Number(value).toFixed(2)} USDT`;
      console.log(tradePanel.innerText, "tradePanel.innerText");
      aTurnoverObersver(value, tab, maxPurch)
    }

  } else {
    console.log("未找到.trade-panel-available > div > span节点");
  }
}

let aTurnoverInputObersver = null

function aTurnoverObersver(value, tab, maxPurch) {
  if (aTurnoverInputObersver) aTurnoverInputObersver.disconnect();
  let previousValues = {
    aTurnoverValue: null
  };
  aTurnoverInputObersver = new MutationObserver(() => {
    const aTurnoverInput = getATurnoverInput(tab)

    if (aTurnoverInput) {
      const hasChanged =
        aTurnoverInput.value !== previousValues.aTurnoverValue

      if (aTurnoverInput && hasChanged) {
        previousValues = {
          aTurnoverValue: aTurnoverInput.value
        }
        const tradePanel = document.querySelector(
          ".panel-limit-price > .mt-3.mx-4 > div > div > span"
        );
        const maxBuy = document.querySelector('.panel-limit-price > .mantine-1ieokwl > .mantine-qi5wjr')
        const numOrBuy = document.querySelector('.panel-limit-price > div > .row-container > .trade-time-price-container > div > .mantine-xubwd9 > .mantine-1tzqd2b > div')
        console.log(maxBuy, numOrBuy, 'maxBuy,numOrBuy');

        console.log(tradePanel, "tradePanel");
        if (tradePanel) {
          if (tab == 'stopByTime' || tab == 'iceberg' || tab == 'loopOrder' || tab == 'stopByTrail') {
            tradePanel.innerText = `${Number(value)} USDT`;
            if (Number(aTurnoverInput.value) > Number(value)) {
              aTurnoverInput.value = value
              aTurnoverInput.dispatchEvent(new Event("input", { bubbles: true }));
            }
          } else {
            if (tab == 'marketPrice' && numOrBuy.innerHTML == '数量') {
              maxBuy.innerHTML = `${Number(maxPurch)} BTC`
              if (Number(aTurnoverInput.value) > Number(maxBuy)) {
                aTurnoverInput.value = maxBuy
                aTurnoverInput.dispatchEvent(new Event("input", { bubbles: true }));
              }
            } else {
              tradePanel.innerText = `${Number(value)} USDT`;
              if (Number(aTurnoverInput.value) > Number(value)) {
                aTurnoverInput.value = value
                aTurnoverInput.dispatchEvent(new Event("input", { bubbles: true }));
              }
            }

          }

          console.log(tradePanel.innerText, "tradePanel.innerText");
        } else {
          console.log("未找到.trade-panel-available > div > span节点");
        }
      }

    }
  });
  aTurnoverInputObersver.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: true,
    characterData: true,
  });
}


function getATurnoverInput(value) {
  if (value == 'limitPrice') {
    return document.querySelector('#trade_spot_limit_amount_input')
  }
  if (value == 'marketPrice') {
    return document.querySelector('#spot-market-price-amount-input')
  }
  if (value == "stopByConditional") {
    return document.querySelectorAll(".trade-input-container > .mantine-1i52ecs > .mantine-ysl0gg")[3]
  }
  if (value == 'stopByTime') {
    return document.querySelector('.trade-input-container > .mantine-1i52ecs > input')
  }
  if (value == 'iceberg') {
    return document.querySelectorAll('.trade-input-container > .mantine-1i52ecs > .mantine-ysl0gg')[2]
  }
  if (value == 'loopOrder') {
    return document.querySelectorAll('.trade-input-container > .mantine-1i52ecs > .mantine-ysl0gg')[3]
  }
  if (value == 'stopByTrail') {
    return document.querySelectorAll('.trade-input-container > .mantine-1i52ecs > .mantine-ysl0gg')[2]
  }
  return null
}

// 最大可买
export function maxPurchasable(value, tab) {
  console.log(tab, value, 'tab,value');

  const maxPurchasable = document.querySelector("#trading_dom > div > div.tab_body > div > div > div.mt-2.mx-4.mantine-1ieokwl > div.mantine-Text-root.mantine-qi5wjr");
  console.log(maxPurchasable, "maxPurchasable");
  if (maxPurchasable) {
    const priceInput = document.querySelectorAll(
      ".mantine-1i52ecs > .mantine-ysl0gg"
    )[0];
    let interval = setInterval(() => {
      if (priceInput && priceInput.value != 0) {
        clearInterval(interval)
        console.log(priceInput.value, "priceInput.value");
        const maxPurch = (Number(value) / Number(priceInput.value)).toFixed(6)
        maxPurchasable.innerText = `${maxPurch} BTC`;
        console.log(maxPurchasable.innerText, "maxPurchasable.innerText");
        // maxPurchasableMutation(maxPurch, tab)
      }
    }, 100)

  } else {
    console.log("未找到.mantine-1ieokwl > div节点");
  }
}

// let maxPurchasObserver = null

// function maxPurchasableMutation(value, tab) {
//   if (maxPurchasObserver) maxPurchasObserver.disconnect();
//   let previousValues = {
//     maxPurchasValue: null
//   };
//   maxPurchasObserver = new MutationObserver(() => {
//     const maxPurchasInput = getNumberInput(tab)

//     if (maxPurchasInput) {
//       const hasChanged =
//         maxPurchasInput.value !== previousValues.maxPurchasValue

//       if (maxPurchasInput && hasChanged) {
//         previousValues = {
//           maxPurchasValue: maxPurchasInput.value
//         }

//         const maxPurchasable = document.querySelectorAll(".mantine-1ieokwl > div")[1];
//         console.log(maxPurchasable, "maxPurchasable");
//         if (maxPurchasable) {
//           maxPurchasable.innerText = `${(Number(value) - Number(previousValues.maxPurchasValue || 0)).toFixed(6) < 0 ? 0 : (Number(value) - Number(previousValues.maxPurchasValue || 0)).toFixed(6)} BTC`;
//           console.log(maxPurchasable.innerText, "maxPurchasable.innerText");
//         } else {
//           console.log("未找到.mantine-1ieokwl > div节点");
//         }
//       }

//     }
//   });
//   maxPurchasObserver.observe(document.body, {
//     childList: true,
//     subtree: true,
//     attributes: true,
//     characterData: true,
//   });
// }

// function getNumberInput(value) {
//   if (value == 'limitPrice') {
//     return document.querySelector('#trade_spot_limit_number_input')
//   }
// }

// 滑动条
export function getSliderValue(svalue) {
  const sliderInput = document.querySelector(
    ".trade-slider-container > .mantine-1dpcsaw > input"
  );
  if (sliderInput) {
    setTimeout(() => {
      const sliderValue = sliderInput.value;
      if (svalue) {
        sliderInput.value = 0.5;
        const event = new Event("input", { bubbles: true });
        sliderInput.dispatchEvent(event);
      }
      return sliderValue;
    }, 100)

  } else {
    console.log("未找到.trade-slider-container > .mantine-1dpcsaw > input节点");
    return null;
  }
}

// 委托价格
export function getEntrustePrice(value) {
  const entrustePriceGroup = document.querySelectorAll(
    ".trade-input-container > .mantine-1i52ecs > .mantine-ysl0gg"
  );
  console.log(entrustePriceGroup, value, "entrustePriceGroup");
  if (entrustePriceGroup) {
    setTimeout(() => {
      const entrustedPrice = entrustePriceGroup[1]
      entrustedPrice.value = value.toFixed(2);
      const event = new Event("input", { bubbles: true });
      entrustedPrice.dispatchEvent(event);
    }, 100)


  }
}
